package nts

import (
	nm "git.oschina.net/go-pkg/nmap/models"
	m "git.oschina.net/go-pkg/nts/models"
)

type nativeHandler struct{}

func (h *nativeHandler) OnNetResult(network string, nmapRun *nm.NmapRun) ([]*m.Dev, bool) {
	var devs []*m.Dev
	for _, host := range nmapRun.Hosts {
		dev := &m.Dev{}
		for _, addr := range host.Addresses {
			if "ipv4" == addr.AddrType {
				dev.IP = addr.Addr
			} else if "mac" == addr.AddrType {
				dev.MAC = addr.Addr
			}
		}
		port := host.Ports[0]
		if "open" == port.State.State {
			dev.IsSnmpRunning = true
		} else {
			dev.IsSnmpRunning = false
		}
		devs = append(devs, dev)
	}
	return devs, true
}

func (h *nativeHandler) OnOsResult(dev *m.Dev, nmapRun *nm.NmapRun) (*m.Dev, bool) {
	if len(nmapRun.Hosts) > 0 {
		host := nmapRun.Hosts[0]
		if len(host.Os.OsMatches) > 0 {
			osmatch := host.Os.OsMatches[0]
			dev.OsName = osmatch.Name
			var devtype string
			var osfamily string
			for _, osclass := range osmatch.OsClasses {
				devtype = osclass.Type
				osfamily = osclass.OsFamily
			}
			if isLocalhost(dev.IP) {
				dev.Type = m.DevTypeAOP
			} else {
				dev.Type = getDevType(devtype)
			}
			dev.OsFamily = osfamily
		} else {
			dev.Type = m.DevTypeHost
		}
	}
	return dev, true
}

func (h *nativeHandler) OnSnmpSvcResult(dev *m.Dev, nmapRun *nm.NmapRun) (*m.Dev, bool) {
	if len(nmapRun.Hosts) > 0 {
		host := nmapRun.Hosts[0]
		debug("host %s, port len %d", dev.IP, len(host.Ports))
		port := host.Ports[0]
		if "open" == port.State.State {
			dev.IsSnmpRunning = true
		} else {
			dev.IsSnmpRunning = false
		}
	}
	return dev, true
}

func getDevType(typeStr string) m.DevType {
	var typ m.DevType
	switch typeStr {
	case "switch":
		typ = m.DevTypeSwitch
	default:
		typ = m.DevTypeHost
	}
	return typ
}
